package com.xiumiing.net.base.net;

import androidx.annotation.NonNull;

import com.google.gson.GsonBuilder;
import com.xiumiing.net.BuildConfig;
import com.xiumiing.net.base.net.interceptor.CacheControlInterceptor;
import com.xiumiing.net.base.net.interceptor.HeaderInterceptor;
import com.xiumiing.net.base.net.rxcalladapter.RxJava2CallAdapterFactory;
import com.xiumiing.net.base.uitls.FileManager;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.xiumiing.net.base.net.interceptor.CacheControlInterceptor.API_CACHE_MAX_SIZE;


/**
 * @author guguofeng
 * @desc RetrofitCreator Retrofit 创建者
 * @date 2019/3/13
 * @Copyright: 武汉市追忆那年网络科技有限公司
 */
public class RetrofitCreator {

    /**
     * api 版本管理
     */
    public final static String API_VERSION = "v1";


    /**
     * 获取Retrofit 对象
     *
     * @param baseUrl String
     * @return Retrofit
     */
    static Retrofit getRetrofit(String baseUrl) {
        return new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(createOkHttpClient())
                .baseUrl(baseUrl)
                .build();
    }

    /**
     * 获取  OkHttpClient 对象
     *
     * @return OkHttpClient
     */
    private static OkHttpClient createOkHttpClient() {
        return new OkHttpClient.Builder()
                .addInterceptor(new HeaderInterceptor())
                .addInterceptor(new CacheControlInterceptor())
                .addInterceptor(new HttpLoggingInterceptor().setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE))
                .retryOnConnectionFailure(true)
                .connectTimeout(Constants.HTTP_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(Constants.HTTP_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(Constants.HTTP_TIMEOUT, TimeUnit.SECONDS)
                .cache(getCache())
                .build();
    }

    /**
     * OkHttp 缓存
     *
     * @return Cache
     */
    @NonNull
    private static Cache getCache() {
        return new Cache(FileManager.getInstance().getFile(FileManager.DIRType.CACHE, "http_cache"), API_CACHE_MAX_SIZE);
    }


    /**
     * OkHttp https 配置
     *
     * @return SSLSocketFactory
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    private static SSLSocketFactory getSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        TrustManager[] trustManagers = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
        sslContext.init(null, trustManagers, new SecureRandom());
        return sslContext.getSocketFactory();
    }


}
